# # #
# client of file trans, send message,and remote control
# 0.0.1
# author: axn
# # #

import socket
import sys, os
from math import ceil

bufSize=4096
#encode='utf-8'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

addr =input("input server address, host port separate by space or : ")
# if host.find(' ')+1 == len(host)
if ' ' in addr:
    host,port=addr.split(' ',1)
elif ':' in addr:
    host,port=addr.split(':',1)
else:
    host=addr
    port=8000
if host=='':
    host='127.0.0.1'
    port=8000
# port = 9999

try:
    port=int(port)
    s.connect((host, port))
    print("connect to {}:{} success".format(host,port) )
except Exception as err:
    print('erro:',err)
    sys.exit(1)


localDir=os.getcwd()
print ( s.recv(1024).decode() , end='')
while True:
    sendMsg=input()
    if sendMsg:
        s.send( sendMsg.encode() )
    else:
        continue
    recvMsg=s.recv(bufSize).decode()
    print(recvMsg,end='')
    
    # 1.quit    
    if sendMsg in ('q','quit','exit') :
        s.close()
        break
    
    elif sendMsg=='wait':
        while True:
            cmd=input(f'{localDir}$$')
            if cmd=='q':
                break
            elif not cmd.find('cd '):
                try:
                    os.chdir(cmd[3:])
                    dir=cmd[3:]
                    print('chang dir OK\n'+dir)
                except Exception as err:
                    print(err)
            # else:
                
    
    # 3.download file
    elif  not (sendMsg.find('get ') and sendMsg.find('down ') ):
        fname=sendMsg.split(' ')[1]
        if 'file size is ' in recvMsg:
            
            fsize=recvMsg.split("file size is ")[1]
            print(fname,fsize)
            # path='./'
        
        # if len(sendMsg.split(' ') > 2:
        

        while True:
            if os.path.isfile(fname):
                tmp=input('file exists, recover[y/r] or type a new name: ')
                if tmp=='y':
                    break
                else:
                    fname=tmp
            else:
                break
                
        # fname=sendMsg.split(' ')[1]+'01'
        with open(fname,'wb') as fp:
            times= ceil( float(fsize)/bufSize )
            for i in range(times):
                dat=s.recv(bufSize)
                fp.write(dat)
            # if '200 ok' in recvMsg.decode():
                    # break
        # print(s.recv(1024).decode() )
        
            
        
    # else:
        # print('sb')
        
        
        